package erp.education.server.beans.implementation.user.transaction;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import erp.education.client.user.transaction.LoginRequest;
import erp.education.server.beans.implementation.BaseService;
import erp.education.server.beans.implementation.ResultResponse;
import erp.education.server.beans.implementation.ServiceObject;
import erp.education.server.beans.implementation.exceptions.ERPException;
import erp.education.server.beans.implementation.exceptions.MessageCode;
import erp.education.server.beans.interfaces.user.transaction.LoginServiceI;
import erp.education.server.beans.interfaces.user.transaction.ServiceObjectI;
import erp.education.server.db.entites.user.Credentials;

@Component("loginService")
public class LoginService extends BaseService implements LoginServiceI {

	@Override
	public ServiceObjectI validateLoginService(LoginRequest loginRequest)
			throws ERPException {
		ServiceObjectI response = new ServiceObject();

		ResultResponse holder = new ResultResponse();
		Credentials user = loginDao.getUser(loginRequest.getAuthenticationId());
		List result = new ArrayList();

		if (null == user) {

			throw new ERPException("Invalid User ", MessageCode.INVALID_USER);
		}

		if (null != user) {
			if (user.getAuthenticationPassword().equals(
					loginRequest.getAuthenticationPassword())) {
				result.add(user);
				if (null == user.getCurrentTheme()) {
					user.setCurrentTheme("base");
				}
				result.add(user.getCurrentTheme());
				holder.setResultList(result);

			} else {

				throw new ERPException("Invalid User ",
						MessageCode.INVALID_USER);

			}
		}
		response.setResponseObject(holder);
		return response;
	}

	@Override
	public ServiceObjectI updateTheme(LoginRequest loginRequest)
			throws ERPException {
		ServiceObjectI response = new ServiceObject();

		ResultResponse holder = new ResultResponse();
		Credentials user = (Credentials) loginRequest.getUserInfo().get("user");
		List result = new ArrayList();
		System.out.println(loginRequest.getThemeName() + "THEME NAME");
		user.setCurrentTheme(loginRequest.getThemeName());

		user = (Credentials) loginDao.merge(user);
		System.out.println(user.getCurrentTheme() + " UPDATED");
		result.add(user);

		result.add(user.getCurrentTheme());
		holder.setResultList(result);

		response.setResponseObject(holder);
		return response;
	}

}
